package servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.CartDao;
import dao.GoodsDao;
import dao.OrderDao;
import dao.Order_itemDao;
import entity.Cart;
import entity.Goods;
import entity.Order;
import entity.Order_item;
import entity.User;

/**
 * Servlet implementation class CheckoutServlet
 */
@WebServlet("/checkout")
public class CheckoutServlet extends HttpServlet {
	private CartDao cartDao = new CartDao();
	private OrderDao orderDao = new OrderDao();
	private Order_itemDao o_itemDao = new Order_itemDao();

	private GoodsDao goodsDao = new GoodsDao();
	private Goods goods = new Goods();
	DecimalFormat df = new DecimalFormat("######0.00");
	Order order = new Order();
	Order_item o_item = new Order_item();
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		
		doPost(req, resp);
	}
	
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("UTF-8");//这是一个坑，前端传数据进来，要先判断它编码是否正确
		resp.setContentType("text/html;charset=UTF-8");// 防止中文乱码
        // 获取Session中的用户uid
        HttpSession session = req.getSession();
        String ud = (String) session.getAttribute("uid");
		
		boolean checkout ;		
		int uid = Integer.parseInt(ud);
		double total_price = 0;//总额
		int gg;
		List<Cart> clist = null;
		try {
			clist = in(uid);
			req.setAttribute("clist", clist);
			List<Goods> glist = cartDao.querByuIdGoods(uid);
			req.setAttribute("glist", glist);
								
			for(Cart cart: clist) {
				gg = cart.getGid();
				goods.setGid(gg);
				try {
					
					goods = goodsDao.queryById(goods);
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}			
				total_price = total_price + goods.getPrice() * cart.getShopnum();
				
				req.setAttribute("total_price", df.format(total_price));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		if( checkout = req.getParameter("act") != null) {
			String oid = getRandom();
			try {
				while(existsOId(oid)) {
					oid = getRandom();
				}
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			//添加订单明细
			for(Cart cart: clist) {
				gg = cart.getGid();
				goods.setGid(gg);
				try {					
					goods = goodsDao.queryById(goods);
					o_item.setOid(oid);
					o_item.setGid(goods.getGid());
					o_item.setG_num(cart.getShopnum());
					o_item.setGname(goods.getGname());
					o_itemDao.addOrder_itemDao(o_item);
					
				} catch (SQLException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}			

			}
			SimpleDateFormat simpleDateFormat;
			simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String date = simpleDateFormat.format(new Date());
			String consigness = req.getParameter("consigness");
			String phone = req.getParameter("phone");
			String address = req.getParameter("address_1") + "--"+ req.getParameter("address_2");
			String remark = req.getParameter("remark");
			order.setOid(oid);
			order.setUid(uid);
			order.setPay_amount(total_price);
			order.setRemark(remark);
			order.setPhone(phone);
			order.setAddress(address);
			order.setConsignee(consigness);
			order.setPay_time(date);
			order.setCreate_time(date);
			order.setPay_status(1);
			
			//新增订单
			try {
				orderDao.addOrder(order);
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}	
			resp.sendRedirect("index"); 
		}else {
			req.getRequestDispatcher("checkout.jsp").forward(req, resp);
		}
		
	}
	
	// 生成订单随机数
	public static String getRandom() {
		String front = "XC";// 前缀
		SimpleDateFormat simpleDateFormat;
		simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
		String date = simpleDateFormat.format(new Date());
		Random random = new Random();
		int rannum = (int) (random.nextDouble() * (99999 - 10000 + 1)) + 10000;
		String rand = front + date + rannum;
		System.out.println(rand);
		
		return rand;
	}

	public boolean existsOId(String oid) throws SQLException {

		if (orderDao.queryByOId(oid) == null) {
			return false;
		}
		return true;
	}
	
	// 从购物车获得订单商品列表
	public List<Cart> in(int uid) throws SQLException {
		// 购物车用户记录
		List<Cart> clist = cartDao.querByuIdCart(uid);
		
		return clist;
	}
	
	//获得商品信息
	public List<Goods> shop(int uid) throws SQLException {
		List<Goods> glist = new ArrayList<Goods>();			
		glist = cartDao.querByuIdGoods(uid);

		return glist;		
	}

}
